package cn.changeforyou.web.cloud.auth.exception;

import cn.changeforyou.base.model.Module;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class RestfulView implements View {

    private int code;
    private String message;

    public RestfulView(int code, String message) {
        this.code = code;
        this.message = message;
    }

    @Override
    public String getContentType() {
        return "application/json;charset=UTF-8";
    }

    @Override
    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType(getContentType());
        response.setStatus(changeCode(code));
        response.getWriter().append(message);
    }

    public int changeCode(int code) {
        if (code / 1000 == Module.AUTH_SERVICE.getCode() / 1000) {
            return 401;
        } else {
            return 500;
        }
    }
}
